using System.Collections.Generic;
using UnityEngine;

namespace CGF
{
    public class UISortingManager 
    {
        public const int LayerJump = 1000;
        public static List<UISortingComponent> allComponents = new List<UISortingComponent>();
        
        public static void SetChildrenSortingOrder(Transform ui, string layerName, int rootOrder)
        {
            for (int i = 0; i < ui.childCount; i++)
            {
                UILayerHelper.SetChildrenSortingOrder(ui.GetChild(i), layerName, ref rootOrder);
            }
        }

        public static bool IsRootCanvasNode(Transform node)
        {
            if (node == UILayerControl.instance.backgroundRoot) return true;
            if (node == UILayerControl.instance.normalRoot) return true;
            if (node == UILayerControl.instance.tipRoot) return true;
            if (node == UILayerControl.instance.topRoot) return true;
            return false;
        }

        /// <summary>
        /// 刷新MainUI全部的UI层级
        /// </summary>
        public static void RefreshAllSorting(Transform layerRoot)
        {
            Canvas layerCanvas = layerRoot.GetComponent<Canvas>();
            string layerName = layerCanvas.sortingLayerName;
            int layerRootSort = layerCanvas.sortingOrder;
            int layerIndex = 0;
            for (int i = 0; i < layerRoot.childCount; i++)
            {
                Transform node = layerRoot.GetChild(i);
                if (node.gameObject.activeSelf)
                {
                    int sort = layerRootSort + layerIndex * LayerJump;
                    Canvas canvas = node.GetComponent<Canvas>();
                    canvas.sortingOrder = sort;
                    for (int j = 0; j < node.childCount; j++)
                    {
                        SetChildrenSortingOrder(node.GetChild(j), layerName, sort);
                    }
                    layerIndex++;
                }
            }
        }
    }
}